package com.wanho.qz103.hrsaas.commons.filter;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.wanho.qz103.hrsaas.commons.util.JwtUtils;
import com.wanho.qz103.hrsaas.commons.vo.R;
import com.wanho.qz103.hrsaas.sys.vo.UserVO;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 执行时机：优先于 Servlet
 */
@WebFilter(filterName = "TokenFilter",urlPatterns = "/api/*")
public class TokenFilter implements Filter {
    /**
     * 初始化
     * @param config
     * @throws ServletException
     */
    public void init(FilterConfig config) throws ServletException {

    }

    /**
     * 执行过滤
     * @param req
     * @param resp
     * @param chain
     * @throws ServletException
     * @throws IOException
     */
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        // 类型向下转换
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        response.setContentType("application/josn;charset=UTF-8");
        // 0 . 排除 无需验证token  登录 如果是登录接口 直接放行
        if ("/api/sys/login".equals(request.getRequestURI())) {
            //放行
            chain.doFilter(request,response);
            return ;
        }
        // 1. 请求头 是否有  Authorization  "Bearer "
        String authorization = request.getHeader("Authorization");
        //没有请求头
        // 如果没有token 返回 响应R.fail("请求格式错误")
        if (StringUtils.isEmpty(authorization)){
            this.printJSON(response,R.fail("请求没有带参数：Authorization"));
            return ;
        }
        try {
            // 2. token 是否过期  JwtUtils 验证方法
            String token = authorization.substring("Bearer ".length()) ;
            JwtUtils.verify(token) ;
            // 放行
            chain.doFilter(req, resp);
            // token 续签  刷新token 1 小时
            // 获得 用户id
           /* DecodedJWT tokenInfo = JwtUtils.getTokenInfo(token);
            String userId = tokenInfo.getClaim("userId").as(String.class);
            // 生成新的 token
            Map<String,String> map = new HashMap<>();
            map.put("userId",userId) ;
            String jwtToken = JwtUtils.createJwtToken(map);
            // 写入 cookie中
            Cookie tokenCookie = new Cookie("hrsaas-ihrm",jwtToken);
            Cookie timeCookie = new Cookie("hrsaas-timestamp-key",new Date().getTime()+"");
            response.addCookie(tokenCookie);
            response.addCookie(timeCookie);*/
        } catch (Exception e) {
            e.printStackTrace();
            // 如果 token 过期 响应 状态码  10002
            this.printJSON(response,R.fail(10002,"token 过期"));
        }
       // System.out.println("===========token 过滤器=======");
    }

    /**
     * 销毁
     */
    public void destroy() {
    }

    private void printJSON(HttpServletResponse response, R r) throws IOException {
        String json = JSON.toJSONString(r);
        PrintWriter writer = response.getWriter();
        writer.write(json);
        writer.flush();
        writer.close();
    }

}
